//
//  LoginController.swift
//  FastFinger
//
//  Created by mugua on 2018/6/26.
//  Copyright © 2018年 mugua. All rights reserved.
//

import UIKit


struct AppDefaultKey {
    
    static let scoreHistorKey = "app.default.scoreHistorKey"
}


class LoginController: UIViewController {
    
    var historInputs: [String] = []
    var inputsModel: String?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(true, animated: animated)
        
        let json = Storage.load(key: AppDefaultKey.scoreHistorKey) as? [String]
        
        if let j = json {
            historInputs = j
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    @IBAction func playTap(_ sender: UIButton) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "GameController")
        
        let altVC = UIAlertController(title: nil, message: "请起个名字", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "加入游戏", style: .default) {[unowned self] (_) in
            
            self.view.endEditing(true)
            
            if let string = self.inputsModel {
             
                if !self.historInputs.contains(string) {
                    
                    self.historInputs.insert(string, at: 0)
                }
            }
            
            SVProgressHUD.show()
            
            SVProgressHUD.dismiss(withDelay: 1.5, completion: {
                self.navigationController?.pushViewController(vc, animated: true)
            })
            
            Storage.save(key: AppDefaultKey.scoreHistorKey, value: self.historInputs)
        }
        
        let cancleAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        altVC.addTextField { [unowned self] (input) in
            input.delegate = self
            self.inputsModel = input.text
        }
        
        altVC.addAction(okAction)
        altVC.addAction(cancleAction)
        
        navigationController?.present(altVC, animated: true, completion: nil)
    }
    
    @IBAction func rankTap(_ sender: UIButton) {
        
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: "RankingListController") as! RankingListController
        
//        vc.dataSouce = historInputs
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension LoginController: UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        self.inputsModel = textField.text
    }
}
